<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="货主" prop="ownerId">
        <el-select v-model="queryParams.ownerId" placeholder="请选择货主" clearable>
          <el-option
            v-for="owner in cargoOwnerList"
            :key="owner.id"
            :label="owner.ownerName"
            :value="owner.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="仓库" prop="warehouseId">
        <el-select v-model="queryParams.warehouseId" placeholder="请选择仓库" clearable>
          <el-option
            v-for="warehouse in warehouseList"
            :key="warehouse.id"
            :label="warehouse.warehouseName"
            :value="warehouse.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="供应商" prop="supplierId">
        <el-select v-model="queryParams.supplierId" placeholder="请选择供应商" clearable>
          <el-option
            v-for="supplier in supplierList"
            :key="supplier.id"
            :label="supplier.supplierName"
            :value="supplier.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in dict.type.wms_receipt_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="预计到货时间" prop="expectedArrivalTime">
        <el-date-picker
          v-model="queryParams.expectedArrivalTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wms:receiptOrder:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wms:receiptOrder:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wms:receiptOrder:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wms:receiptOrder:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="receiptOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderNo" width="180" />
      <el-table-column label="货主名称" align="center" prop="ownerName" />
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="供应商名称" align="center" prop="supplierName" />
      <el-table-column label="预计到货时间" align="center" prop="expectedArrivalTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expectedArrivalTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_receipt_order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['wms:receiptOrder:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wms:receiptOrder:edit']"
            v-if="scope.row.status === 'PENDING'"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleConfirm(scope.row)"
            v-hasPermi="['wms:receiptOrder:confirm']"
            v-if="scope.row.status === 'PENDING' || scope.row.status === 'RECEIVING' || scope.row.status === 'PARTIALLY_RECEIVED'"
          >收货</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="handleCancel(scope.row)"
            v-hasPermi="['wms:receiptOrder:cancel']"
            v-if="scope.row.status === 'PENDING' || scope.row.status === 'RECEIVING' || scope.row.status === 'PARTIALLY_RECEIVED'"
          >取消</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wms:receiptOrder:remove']"
            v-if="scope.row.status === 'PENDING'"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改收货订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="货主" prop="ownerId">
              <el-select v-model="form.ownerId" placeholder="请选择货主" style="width: 100%" @change="handleOwnerChange">
                <el-option
                  v-for="owner in cargoOwnerList"
                  :key="owner.id"
                  :label="owner.ownerName"
                  :value="owner.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单编号" prop="orderNo">
              <el-input v-model="form.orderNo" placeholder="请输入订单编号" :disabled="form.orderId != null">
                <el-button slot="append" icon="el-icon-refresh" @click="generateOrderNo" v-if="form.orderId == null">生成</el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库" prop="warehouseId">
              <el-select v-model="form.warehouseId" placeholder="请选择仓库" style="width: 100%" @change="handleWarehouseChange">
                <el-option
                  v-for="warehouse in warehouseList"
                  :key="warehouse.id"
                  :label="warehouse.warehouseName"
                  :value="warehouse.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="供应商" prop="supplierId">
              <el-select v-model="form.supplierId" placeholder="请选择供应商" style="width: 100%" @change="handleSupplierChange">
                <el-option
                  v-for="supplier in supplierList"
                  :key="supplier.id"
                  :label="supplier.supplierName"
                  :value="supplier.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预计到货时间" prop="expectedArrivalTime">
              <el-date-picker
                v-model="form.expectedArrivalTime"
                type="datetime"
                placeholder="选择预计到货时间"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单状态" prop="status" v-if="form.orderId != null">
              <el-select v-model="form.status" placeholder="请选择订单状态" style="width: 100%" disabled>
                <el-option
                  v-for="dict in dict.type.wms_receipt_order_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 订单明细 -->
        <el-divider content-position="left">订单明细</el-divider>
        <div class="mb8">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddDetail">添加明细</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteDetail" :disabled="!selectedDetailIds.length">删除明细</el-button>
        </div>
        
        <el-table :data="form.detailList" @selection-change="handleDetailSelectionChange" border>
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" type="index" width="50" align="center" />
          <el-table-column label="商品编码" prop="skuCode" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.skuCode" placeholder="请输入商品编码" size="mini" @blur="handleSkuCodeBlur(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column label="商品名称" prop="skuName" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.skuName" placeholder="请输入商品名称" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="预期数量" prop="expectedQty" width="140">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.expectedQty" :min="0" :precision="2" size="mini" style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column label="实收数量" prop="actualQty" width="100" v-if="form.orderId != null">
            <template slot-scope="scope">
              <span>{{ scope.row.actualQty || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="unit" width="80">
            <template slot-scope="scope">
              <el-input v-model="scope.row.unit" placeholder="单位" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="批次号" prop="batchNo" width="160">
            <template slot-scope="scope">
              <el-input v-model="scope.row.batchNo" placeholder="请输入批次号" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="生产日期" prop="productionDate" width="120">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.productionDate"
                type="date"
                placeholder="生产日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                size="mini"
                style="width: 100%"
              ></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="过期日期" prop="expirationDate" width="120">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.expirationDate"
                type="date"
                placeholder="过期日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                size="mini"
                style="width: 100%"
              ></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="行状态" prop="lineStatus" width="100" v-if="form.orderId != null">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.wms_receipt_detail_status" :value="scope.row.lineStatus"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleRemoveDetail(scope.$index)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 收货确认对话框 -->
    <el-dialog title="收货确认" :visible.sync="confirmOpen" width="1000px" append-to-body>
      <el-form ref="confirmForm" :model="confirmForm" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="订单编号">
              <el-input v-model="confirmForm.orderNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="货主名称">
              <el-input v-model="confirmForm.ownerName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库名称">
              <el-input v-model="confirmForm.warehouseName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">收货明细</el-divider>
        <el-table :data="confirmForm.detailList" border>
          <el-table-column label="序号" type="index" width="50" align="center" />
          <el-table-column label="商品编码" prop="skuCode" width="120" />
          <el-table-column label="商品名称" prop="skuName" width="150" />
          <el-table-column label="预期数量" prop="expectedQty" width="100" />
          <el-table-column label="已收数量" prop="actualQty" width="100" />
          <el-table-column label="本次收货" prop="receiptQty" width="120">
            <template slot-scope="scope">
              <el-input-number 
                v-model="scope.row.receiptQty" 
                :min="0" 
                :max="scope.row.expectedQty - scope.row.actualQty"
                :precision="2" 
                size="mini" 
                style="width: 100%" 
              />
            </template>
          </el-table-column>
          <el-table-column label="推荐库位" prop="recommendedLocation" width="200">
            <template slot-scope="scope">
              <div style="display: flex; align-items: center; gap: 5px;">
                <el-input 
                  v-model="scope.row.recommendedLocationCode" 
                  placeholder="请输入库位编码" 
                  size="mini" 
                  style="flex: 1" 
                  @blur="handleLocationCodeBlur(scope.row)"
                />
                <el-button 
                  v-if="scope.row.systemRecommendedLocationCode" 
                  size="mini" 
                  type="text" 
                  @click="useRecommendedLocation(scope.row)"
                  title="使用推荐库位"
                >
                  推荐
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="unit" width="80" />
          <el-table-column label="批次号" prop="batchNo" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.batchNo" placeholder="请输入批次号" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="生产日期" prop="productionDate" width="120">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.productionDate"
                type="date"
                placeholder="生产日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                size="mini"
                style="width: 100%"
              ></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="过期日期" prop="expirationDate" width="120">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.expirationDate"
                type="date"
                placeholder="过期日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                size="mini"
                style="width: 100%"
              ></el-date-picker>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitConfirm">确认收货</el-button>
        <el-button @click="confirmOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" :visible.sync="detailOpen" width="1200px" append-to-body>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="订单编号">{{ detailForm.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="货主名称">{{ detailForm.ownerName }}</el-descriptions-item>
        <el-descriptions-item label="仓库名称">{{ detailForm.warehouseName }}</el-descriptions-item>
        <el-descriptions-item label="供应商名称">{{ detailForm.supplierName }}</el-descriptions-item>
        <el-descriptions-item label="预计到货时间">{{ parseTime(detailForm.expectedArrivalTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <dict-tag :options="dict.type.wms_receipt_order_status" :value="detailForm.status"/>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(detailForm.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ detailForm.createBy }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="3">{{ detailForm.remark }}</el-descriptions-item>
      </el-descriptions>
      
      <el-divider content-position="left">订单明细</el-divider>
      <el-table :data="detailForm.detailList" border>
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="商品编码" prop="skuCode" width="120" />
        <el-table-column label="商品名称" prop="skuName" width="150" />
        <el-table-column label="预期数量" prop="expectedQty" width="100" />
        <el-table-column label="实收数量" prop="actualQty" width="100" />
        <el-table-column label="单位" prop="unit" width="80" />
        <el-table-column label="批次号" prop="batchNo" width="120" />
        <el-table-column label="生产日期" prop="productionDate" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.productionDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="过期日期" prop="expirationDate" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.expirationDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="行状态" prop="lineStatus" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.wms_receipt_detail_status" :value="scope.row.lineStatus"/>
          </template>
        </el-table-column>
      </el-table>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReceiptOrder, getReceiptOrder, delReceiptOrder, addReceiptOrder, updateReceiptOrder, confirmReceipt, cancelReceiptOrder, completeReceiptOrder, generateOrderNo, getRecommendedLocation } from "@/api/wms/receiptOrder";
import { getItemByCode } from "@/api/wms/item";
import { listCargoOwner } from "@/api/wms/cargoOwner";
import { listWarehouse } from "@/api/wms/warehouse";
import { listSupplier } from "@/api/wms/supplier";
import { getLocationByCode } from "@/api/wms/location";

export default {
  name: "ReceiptOrder",
  dicts: ['wms_receipt_order_status', 'wms_receipt_detail_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 收货订单表格数据
      receiptOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示收货确认对话框
      confirmOpen: false,
      // 是否显示详情对话框
      detailOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: null,
        ownerId: null,
        warehouseId: null,
        supplierId: null,
        status: null,
        expectedArrivalTime: null
      },
      // 表单参数
      form: {
        detailList: []
      },
      // 收货确认表单
      confirmForm: {
        detailList: []
      },
      // 详情表单
      detailForm: {
        detailList: []
      },
      // 表单校验
      rules: {
        orderNo: [
          { required: true, message: "订单编号不能为空", trigger: "blur" }
        ],
        ownerId: [
          { required: true, message: "货主不能为空", trigger: "change" }
        ],
        warehouseId: [
          { required: true, message: "仓库不能为空", trigger: "change" }
        ],
        supplierId: [
          { required: true, message: "供应商不能为空", trigger: "change" }
        ],
        expectedArrivalTime: [
          { required: true, message: "预计到货时间不能为空", trigger: "blur" }
        ]
      },
      // 货主列表
      cargoOwnerList: [],
      // 仓库列表
      warehouseList: [],
      // 供应商列表
      supplierList: [],
      // 选中的明细ID
      selectedDetailIds: []
    };
  },
  created() {
    this.getList();
    this.getCargoOwnerList();
    this.getWarehouseList();
    this.getSupplierList();
  },
  methods: {
    /** 查询收货订单列表 */
    getList() {
      this.loading = true;
      listReceiptOrder(this.queryParams).then(response => {
        this.receiptOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询货主列表 */
    getCargoOwnerList() {
      listCargoOwner({ status: '0' }).then(response => {
        this.cargoOwnerList = response.rows;
      });
    },
    /** 查询仓库列表 */
    getWarehouseList() {
      listWarehouse({ status: '0' }).then(response => {
        this.warehouseList = response.rows;
      });
    },
    /** 查询供应商列表 */
    getSupplierList() {
      listSupplier({ status: '0' }).then(response => {
        this.supplierList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        orderNo: null,
        ownerId: null,
        ownerName: null,
        warehouseId: null,
        warehouseName: null,
        supplierId: null,
        supplierName: null,
        expectedArrivalTime: null,
        status: "PENDING",
        remark: null,
        detailList: []
      };
      this.selectedDetailIds = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 明细多选框选中数据
    handleDetailSelectionChange(selection) {
      this.selectedDetailIds = selection.map((item, index) => index);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加收货订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId || this.ids
      getReceiptOrder(orderId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改收货订单";
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      getReceiptOrder(row.orderId).then(response => {
        this.detailForm = response.data;
        this.detailOpen = true;
      });
    },
    /** 收货确认按钮操作 */
    handleConfirm(row) {
      getReceiptOrder(row.orderId).then(response => {
        this.confirmForm = response.data;
        // 初始化收货数量，默认等于预期数量减去已收数量
        this.confirmForm.detailList.forEach(item => {
          item.receiptQty = (item.expectedQty || 0) - (item.actualQty || 0);
        });
        // 获取推荐库位
        this.loadRecommendedLocations();
        this.confirmOpen = true;
      });
    },
    /** 取消订单按钮操作 */
    handleCancel(row) {
      this.$modal.confirm('是否确认取消订单编号为"' + row.orderNo + '"的收货订单？').then(function() {
        return cancelReceiptOrder(row.orderId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("取消成功");
      }).catch(() => {});
    },
    /** 提交按钮 */
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          if (this.form.detailList.length === 0) {
            this.$modal.msgError("请至少添加一条订单明细");
            return;
          }
          
          // 校验明细行数据
          for (let i = 0; i < this.form.detailList.length; i++) {
            const detail = this.form.detailList[i];
            if (!detail.skuCode || detail.skuCode.trim() === '') {
              this.$modal.msgError(`第${i + 1}行明细的商品编码不能为空`);
              return;
            }
            // 校验预期数量必须大于0
            if (!detail.expectedQty || detail.expectedQty <= 0) {
              this.$modal.msgError(`第${i + 1}行明细的预期数量必须大于0`);
              return;
            }
            // 移除itemId的校验，因为后面会通过skuCode查询获取itemId
          }
          
          try {
            // 处理明细数据，将skuCode映射为itemId
            const formData = { ...this.form };
            const detailPromises = this.form.detailList.map(async detail => {
              const mappedDetail = { ...detail };
              // 通过商品编码查询商品ID（无论itemId是否已存在都重新查询确保数据正确）
              if (detail.skuCode) {
                try {
                  const response = await getItemByCode(detail.skuCode);
                  if (response.code === 200 && response.data) {
                    mappedDetail.itemId = response.data.id;
                    mappedDetail.skuName = response.data.itemName; // 同时设置商品名称
                  } else {
                    this.$modal.msgError(`商品编码 ${detail.skuCode} 不存在`);
                    throw new Error(`商品编码 ${detail.skuCode} 不存在`);
                  }
                } catch (error) {
                  this.$modal.msgError(`查询商品编码 ${detail.skuCode} 失败`);
                  throw error;
                }
              } else {
                this.$modal.msgError(`明细行缺少商品编码`);
                throw new Error(`明细行缺少商品编码`);
              }
              
              // 移除skuCode字段，因为后端表结构中没有这个字段
              delete mappedDetail.skuCode;
              
              return mappedDetail;
            });
            
            formData.detailList = await Promise.all(detailPromises);
            
            if (this.form.orderId != null) {
              updateReceiptOrder(formData).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addReceiptOrder(formData).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          } catch (error) {
            // 错误已在上面处理，这里不需要额外操作
            return;
          }
        }
      });
    },
    /** 收货确认提交 */
    submitConfirm() {
      // 验证收货数量
      let hasReceiptQty = false;
      for (let item of this.confirmForm.detailList) {
        if (item.receiptQty > 0) {
          hasReceiptQty = true;
          break;
        }
      }
      if (!hasReceiptQty) {
        this.$modal.msgError("请输入收货数量");
        return;
      }
      
      confirmReceipt(this.confirmForm).then(response => {
        this.$modal.msgSuccess("收货确认成功");
        this.confirmOpen = false;
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除收货订单编号为"' + orderIds + '"的数据项？').then(function() {
        return delReceiptOrder(orderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wms/receiptOrder/export', {
        ...this.queryParams
      }, `receiptOrder_${new Date().getTime()}.xlsx`)
    },
    /** 生成订单编号 */
    generateOrderNo() {
      if (!this.form.ownerId) {
        this.$modal.msgError("请先选择货主");
        return;
      }
      generateOrderNo(this.form.ownerId).then(response => {
        this.form.orderNo = response.data;
      });
    },
    /** 货主变更处理 */
    handleOwnerChange(ownerId) {
      const owner = this.cargoOwnerList.find(item => item.id === ownerId);
      if (owner) {
        this.form.ownerName = owner.ownerName;
      }
    },
    /** 仓库变更处理 */
    handleWarehouseChange(warehouseId) {
      const warehouse = this.warehouseList.find(item => item.id === warehouseId);
      if (warehouse) {
        this.form.warehouseName = warehouse.warehouseName;
      }
    },
    /** 供应商变更处理 */
    handleSupplierChange(supplierId) {
      const supplier = this.supplierList.find(item => item.id === supplierId);
      if (supplier) {
        this.form.supplierName = supplier.supplierName;
      }
    },
    /** 添加明细 */
    handleAddDetail() {
      this.form.detailList.push({
        itemId: null,
        skuCode: '',
        skuName: '',
        expectedQty: 0,
        actualQty: 0,
        unit: '',
        batchNo: '',
        productionDate: null,
        expirationDate: null,
        lineStatus: 'PENDING'
      });
    },
    /** 删除选中明细 */
    handleDeleteDetail() {
      // 从后往前删除，避免索引变化
      for (let i = this.selectedDetailIds.length - 1; i >= 0; i--) {
        this.form.detailList.splice(this.selectedDetailIds[i], 1);
      }
      this.selectedDetailIds = [];
    },
    /** 移除明细 */
    handleRemoveDetail(index) {
      this.form.detailList.splice(index, 1);
    },
    /** 处理商品编码失去焦点事件 */
    async handleSkuCodeBlur(row) {
      if (row.skuCode && row.skuCode.trim() !== '') {
        try {
          const response = await getItemByCode(row.skuCode.trim());
          if (response.code === 200 && response.data) {
            row.itemId = response.data.id;
            row.skuName = response.data.itemName;
            row.unit = response.data.unit || row.unit;
          } else {
            this.$modal.msgError(`没有${row.skuCode}商品`);
            row.skuName = '';
            row.itemId = null;
          }
        } catch (error) {
          console.error('查询商品信息失败:', error);
          this.$modal.msgError(`查询商品编码 ${row.skuCode} 失败`);
        }
      }
    },
    /** 加载推荐库位 */
    async loadRecommendedLocations() {
      if (!this.confirmForm.detailList || this.confirmForm.detailList.length === 0) {
        return;
      }
      
      for (let item of this.confirmForm.detailList) {
        if (item.itemId && this.confirmForm.warehouseId) {
          try {
            const response = await getRecommendedLocation(item.itemId, this.confirmForm.warehouseId);
            if (response.code === 200 && response.data) {
              item.recommendedLocationId = response.data.id;
              // 保存系统推荐的库位编码，用于显示推荐按钮
              item.systemRecommendedLocationCode = response.data.locationCode;
              // 如果用户还没有输入库位编码，则使用推荐的库位编码
              if (!item.recommendedLocationCode) {
                item.recommendedLocationCode = response.data.locationCode;
              }
            } else {
              item.recommendedLocationId = null;
              item.systemRecommendedLocationCode = '';
              item.recommendedLocationCode = item.recommendedLocationCode || '';
            }
          } catch (error) {
            console.error('获取推荐库位失败:', error);
            item.recommendedLocationId = null;
            item.systemRecommendedLocationCode = '';
            item.recommendedLocationCode = item.recommendedLocationCode || '';
            // 如果是"请维护一个临时库位"的错误，显示给用户
            if (error.response && error.response.data && error.response.data.msg) {
              this.$modal.msgError(error.response.data.msg);
            }
          }
        }
      }
    },
    /** 使用推荐库位 */
    useRecommendedLocation(row) {
      if (row.systemRecommendedLocationCode) {
        row.recommendedLocationCode = row.systemRecommendedLocationCode;
        // 同时设置推荐库位ID
        row.recommendedLocationId = row.recommendedLocationId;
      }
    },
    /** 处理库位编码失去焦点事件 */
    async handleLocationCodeBlur(row) {
      if (row.recommendedLocationCode && row.recommendedLocationCode.trim() !== '') {
        row.recommendedLocationCode = row.recommendedLocationCode.trim();
        
        try {
           // 调用API校验库位编码
           const response = await getLocationByCode(row.recommendedLocationCode);
          if (response.code === 200 && response.data) {
            // 校验库位是否属于当前仓库
            if (response.data.warehouseId !== this.confirmForm.warehouseId) {
              this.$modal.msgError(`库位编码 ${row.recommendedLocationCode} 不属于当前仓库`);
              row.recommendedLocationCode = '';
              return;
            }
            // 库位编码有效，设置库位ID
            row.recommendedLocationId = response.data.id;
            this.$modal.msgSuccess(`库位编码 ${row.recommendedLocationCode} 校验通过`);
          } else {
            this.$modal.msgError(`库位编码 ${row.recommendedLocationCode} 不存在`);
            row.recommendedLocationCode = '';
            row.recommendedLocationId = null;
          }
        } catch (error) {
          console.error('校验库位编码失败:', error);
          this.$modal.msgError(`校验库位编码 ${row.recommendedLocationCode} 失败`);
          row.recommendedLocationCode = '';
          row.recommendedLocationId = null;
        }
      }
    }
  }
};
</script>